<script lang="ts" setup>
  import {
    PlusOutlined,
    SearchOutlined
  } from '@ant-design/icons-vue';
  import { reactive, ref, onMounted } from 'vue';
  import { FormInstance, message, TableProps } from 'ant-design-vue';
  import { useAuthStore } from '@/plugins';
  import http from '@/store/http';
  import { Response } from '@/types';

  const { useAuth } = useAuthStore();

  const columns = [
    {
      title: '用户名',
      dataIndex: 'username',
    },
    {
      title: '密码',
      dataIndex: 'password',
    },
    {
      title: '角色',
      dataIndex: 'roleList',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '创建时间',
      dataIndex: 'createUser',
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
    },
    {
      title: '创建时间',
      dataIndex: 'updateUser',
    },
    {
      width: 140,
      title: '操作',
      align: 'center',
      dataIndex: 'operation',
    },
  ];

  const loading = ref(false);

  const showForm = ref(false);

  const queryFormData = ref({
    username: '',
  });

  interface Role {
    name: string;
    id: number;
    title: string;
  }

  interface User {
    id?: number;
    username: string;
    password: string;
    roleList: number[];
  }

  const userList = ref<User[]>();

  const formData = reactive<User>({
    id: undefined,
    username: '',
    password: undefined,
    roleList: [],
  });

  const updateUser = (user: User) => {
    form.value.validateFields().then(() => {
      http.request<String, Response<String>>('/api/user', 'put_json', formData).then(res => {
        const { code, msg } = res;
        if (code !== 200) {
          message.error(msg);
          return;
        }
        message.success(msg);
        showForm.value = false;
        getUserList();
      });
    });
  };

  const addUser = (user: User) => {
    form.value.validateFields().then(() => {
      http.request<String, Response<String>>('/api/user', 'post_json', formData).then(res => {
        const { code, msg } = res;
        if (code !== 200) {
          message.error(msg);
          return;
        }
        message.success(msg);
        showForm.value = false;
        getUserList();
      });
    });
  };

  const form = ref<FormInstance>();

  function submit() {
    loading.value = true;
    form.value
      ?.validate()
      .then(() => {
        formData.id ? updateUser(formData) : addUser(formData);
        showForm.value = false;
      })
      .finally(() => {
        loading.value = false;
      });
  }

  const title = ref('新增角色');

  const edit = useAuth('admin', function(record: User) {
    form.value?.resetFields();
    formData.id = record.id;
    formData.username = record.username;
    formData.password = record.password;
    formData.roleList = record.roleList;
    showForm.value = true;
    title.value = '编辑角色';
  });

  function add() {
    form.value?.resetFields();
    formData.id = undefined;
    formData.username = '';
    formData.password = undefined;
    showForm.value = true;
    title.value = '新增角色';
  }

  const removeUser = (user: User) => {
    http.request<String, Response<String>>('/api/user/' + user.id, 'delete').then(res => {
      const { code, msg } = res;
      if (code !== 200) {
        message.error(msg);
        return;
      }
      message.success(msg);
      showForm.value = false;
      getUserList();
    });
  };

  onMounted(() => {
    getUserList();
  });

  interface Page<T> {
    records: T[];
    total: number;
    current: number;
  }

  const getUserList = () => {
    http.request<Page<User>, Response<Page<User>>>('/api/user/page', 'get',
      {
        username: queryFormData.value.username,
        current: current.value,
        size: size.value,
      }).then(res => {
      const { code, data } = res;
      if (code === 200) {
        userList.value = data.records;
        total.value = data.total;
      }
    });
  };

  const tableChange: TableProps['onChange'] = (pagination) => {
    current.value = pagination.current;
    getUserList();
  };


  const size = ref(10);
  const current = ref(1);
  const total = ref(0);

  const roleOptions = ref([]);

  http.request<Role[], Response<Role[]>>('api/role', 'get').then(res => {
    roleOptions.value = res.data.map((role) => {
      return {
        label: role.title,
        value: role.id,
      };
    });
  });
</script>
<template>
  <div class="authority">
    <a-table
      rowKey="id"
      :columns="columns"
      :dataSource="userList"
      :pagination="{ pageSize: size, current: current, total: total }"
      @change="tableChange"
    >
      <template #title>
        <div class="flex justify-between">
          角色信息
          <div class="flex">
            <a-form-item name="username" label="用户名">
              <a-input v-model:value="queryFormData.username" />
            </a-form-item>
            <a-button @click="getUserList">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>
            <a-button type="primary" @click="add">
              <template #icon>
                <PlusOutlined />
              </template>
              新增
            </a-button>
          </div>
        </div>
      </template>
      <template #bodyCell="{ text, record, index, column }">
        <template v-if="column.dataIndex === 'operation'">
          <a-button class="text-xs" type="primary" size="small" @click="edit(record)">编辑</a-button>
          <a-popconfirm title="确认删除？" @confirm="removeUser(record)">
            <a-button class="text-xs ml-base" danger size="small">删除</a-button>
          </a-popconfirm>
        </template>
        <template v-else-if="column.dataIndex === 'roleList'">
          <template v-for="roleId in record.roleList">
            <a-tag color="blue">{{ roleOptions.filter(item => item.value === roleId)[0].label }}</a-tag>
          </template>
        </template>
        <template v-else-if="column.dataIndex === 'icon'">
          <component :is="record.icon" />
        </template>
      </template>
    </a-table>
    <a-modal :okButtonProps="{ loading }" width="540px" v-model:visible="showForm" :title="title" @ok="submit">
      <a-form ref="form" :model="formData" :labelCol="{ span: 5 }" :wrapperCol="{ span: 16, offset: 1 }">
        <a-form-item required name="username" label="用户">
          <a-input v-model:value="formData.username" :disabled="formData.id" />
        </a-form-item>
        <a-form-item required name="password" label="密码">
          <a-input type="password" v-model:value="formData.password" />
        </a-form-item>
        <a-form-item name="roleList" label="角色">
          <a-select
            v-model:value="formData.roleList"
            mode="multiple"
            :options="roleOptions"
          ></a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
